<template>
    <view class="container">
        <view class="title">模拟通话系统</view>
        
        <!-- 虚拟号码选择区域 -->
        <view class="virtual-section">
            <text>选择您的虚拟号码：</text>
            <!-- 下拉选择器：增加v-if确保数据加载后再渲染，避免空数组问题 -->
            <picker 
                v-if="filteredVirtualPhones.length > 0"
                @change="onVirtualPhoneChange" 
                :value="selectedIndex"
                :range="filteredVirtualPhones"
                :range-key="'virtualphoneNumber'"
            >
                <view class="picker-display">
                    {{ selectedIndex !== -1 
                      ? filteredVirtualPhones[selectedIndex].virtualphoneNumber 
                      : '请选择虚拟号码' 
                    }}
                </view>
            </picker>
            <!-- 无可用号码时显示提示 -->
            <view class="no-phone-tip" v-else>
                暂无可用虚拟号码
            </view>
            
            <!-- 选中的虚拟号码详情：增加安全判断 -->
            <view class="virtual-detail" v-if="selectedVirtualPhone">
                <text>号码地址：{{ selectedVirtualPhone.virtualphoneAddress || '未知' }}</text>
                <text>通话单价：{{ selectedVirtualPhone.pay || 0 }} 元/分钟</text>
            </view>
        </view>
        
        <view class="input-section">
            <text>请输入要呼叫的号码：</text>
            <input 
                v-model="targetPhone" 
                type="number" 
                placeholder="输入目标手机号"
                maxlength="11"
            />
        </view>
        
        <!-- 呼叫按钮：增加可用号码判断 -->
        <button 
            class="call-btn" 
            @click="startCall"
            :disabled="!selectedVirtualPhone || !targetPhone || filteredVirtualPhones.length === 0"
        >
            开始呼叫
        </button>
    </view>
</template>

<script>
// 关键修复：确认API引入路径正确！
// 若 virtualPhoneApi 单独放在 virtualPhoneApi.js 中，路径应为 '../../api/virtualPhoneApi.js'
// 若放在 userApi.js 中，需确保 userApi.js 内确实导出了 virtualPhoneApi
import { virtualPhoneApi } from '../../api/userApi.js'; 

export default {
    data() {
        return {
            targetPhone: '',
            virtualPhones: [], // 所有虚拟号码
            filteredVirtualPhones: [], // 过滤后启用的号码（status=1）
            selectedIndex: -1, // 选中索引（初始未选中）
            selectedVirtualPhone: null // 选中的号码详情
        };
    },
    onLoad() {
        this.fetchVirtualPhones(); // 加载虚拟号码列表
    },
    methods: {
        // 获取虚拟号码列表：优化错误捕获和状态提示
        async fetchVirtualPhones() {
            try {
                uni.showLoading({ title: '加载虚拟号码中...' });
                const res = await virtualPhoneApi.getVirtualPhoneList();
                
                // 严格判断后端响应格式（避免非预期数据）
                if (res && res.code === 0 && Array.isArray(res.data)) {
                    this.virtualPhones = res.data;
                    // 过滤仅启用的号码（status=1）
                    this.filteredVirtualPhones = res.data.filter(phone => 
                        phone.status === 1
                    );
                    console.log('可用虚拟号码：', this.filteredVirtualPhones);
                } else {
                    uni.showToast({ title: '获取号码失败', icon: 'none', duration: 1500 });
                }
            } catch (error) {
                console.error('获取虚拟号码错误：', error);
                // 区分网络错误和接口错误
                const errMsg = error.message.includes('fail') ? '网络连接失败' : '接口请求错误';
                uni.showToast({ title: errMsg, icon: 'none', duration: 1500 });
            } finally {
                uni.hideLoading(); // 无论成功失败，都关闭加载提示
            }
        },
        
        // 选择虚拟号码：增加安全索引判断
        onVirtualPhoneChange(e) {
            const index = e.detail.value;
            // 防止索引越界（极端情况）
            if (index >= 0 && index < this.filteredVirtualPhones.length) {
                this.selectedIndex = index;
                this.selectedVirtualPhone = this.filteredVirtualPhones[index];
                // 保存到本地缓存
                uni.setStorageSync('myPhone', this.selectedVirtualPhone.virtualphoneNumber);
            }
        },
        
        // 开始呼叫：增加参数编码（避免特殊字符问题）
        startCall() {
            // 编码参数（防止号码含特殊字符导致跳转异常）
            const myPhone = encodeURIComponent(this.selectedVirtualPhone.virtualphoneNumber);
            const targetPhone = encodeURIComponent(this.targetPhone);
			const pay = encodeURIComponent(this.selectedVirtualPhone.pay)
            
            uni.navigateTo({
                url: `/pages/calling/index?myPhone=${myPhone}&targetPhone=${targetPhone}&pay=${pay}`
            });
        }
    }
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    padding: 20rpx;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.title {
    font-size: 36rpx;
    text-align: center;
    margin: 50rpx 0;
    font-weight: bold;
    color: #333;
}

/* 虚拟号码选择区域 */
.virtual-section {
    margin-bottom: 30rpx;
    display: flex;
    flex-direction: column;
    gap: 10rpx;
}

.virtual-section text:first-child {
    font-size: 28rpx;
    color: #333;
}

/* 选择器样式 */
.picker-display {
    height: 80rpx;
    line-height: 80rpx;
    border: 1px solid #ddd;
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    background-color: #fff;
    color: #333;
}

/* 无号码提示 */
.no-phone-tip {
    height: 80rpx;
    line-height: 80rpx;
    border: 1px dashed #ccc;
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 26rpx;
    color: #999;
    text-align: center;
    background-color: #fff;
}

/* 号码详情 */
.virtual-detail {
    margin-top: 15rpx;
    padding: 15rpx 20rpx;
    background-color: #fff;
    border-radius: 10rpx;
    font-size: 26rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.virtual-detail text {
    display: block;
    margin-bottom: 8rpx;
    color: #666;
}

/* 目标号码输入 */
.input-section {
    margin-bottom: 30rpx;
    display: flex;
    flex-direction: column;
    gap: 10rpx;
}

.input-section text {
    font-size: 28rpx;
    color: #333;
}

.input-section input {
    height: 80rpx;
    border: 1px solid #ddd;
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    background-color: #fff;
}

/* 呼叫按钮 */
.call-btn {
    background-color: #007aff;
    color: white;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    margin-top: 50rpx;
    border-radius: 10rpx;
}

/* 按钮禁用样式（增强视觉反馈） */
.call-btn[disabled] {
    background-color: #c0c0c0 !important;
    color: #fff !important;
}
</style>